package controllers;


import models.*;
import org.springframework.beans.factory.annotation.Autowired;
import play.data.Form;
import play.mvc.*;
import services.ProductService;
import views.html.product.indexProduct;
import views.html.product.editProduct;
import views.html.product.addProduct;
import java.util.List;

/**
 * Created by MANHCUONG on 12/26/13.
 */

@org.springframework.stereotype.Controller
public class ProductController extends Controller {
    @Autowired
    private ProductService productService;
    private String valueSearch;

    public Result allProducts(){
        valueSearch = "";
        List<Product> proList = productService.getAllProducts();
        return ok(indexProduct.render("List of Products", proList, valueSearch));
    }

    public  Result editProduct(int id){
        Form<Product> f = new Form<Product>(Product.class);
        Product product=productService.getProductById(new Integer(id));
        Form<Product> fNew= f.fill(product);
        return ok(editProduct.render("Edit Product", fNew));
    }

    public Result createProduct() {
        Form<Product> f = new Form<Product>(Product.class);
        return ok(addProduct.render("Create Orders", f));
    }

    public Result addProduct(){
        Form<Product> f = Form.form(Product.class).bindFromRequest();
        if(f.hasErrors()){
            return badRequest(addProduct.render("List of Products", f));
        } else {
            Product pro = f.get();
            productService.insertProduct(pro);
            return redirectUtil(valueSearch);
        }
    }

    public Result updateProduct(){
        Form<Product> f = Form.form(Product.class).bindFromRequest();
        if(f.hasErrors()){
            return badRequest(editProduct.render("Update fail", f));
        } else {
            Product pro = f.get();
            productService.updateProduct(pro);
            return redirectUtil(valueSearch);
        }
    }

    public Result deleteProduct (int id) {
        productService.deleteProduct(id);
        return redirectUtil(valueSearch);
    }
    private Result redirectUtil(String filter){
        if (!filter.equals(null) && !filter.equals("")){
            List<Product> cusList = productService.getProductsLikeName("%" + filter.trim() + "%");
            return ok(indexProduct.render("List of Customers", cusList, filter));
        }
        return redirect(routes.ProductController.allProducts());
    }
}
